package com.knowswift.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.knowswift.common.bean.issue.po.Issue;
import com.knowswift.common.bean.issue.po.MonitorDevice;
import com.knowswift.common.bean.issue.po.MonitorRecord;
import com.knowswift.common.bean.project.po.Module;
import com.knowswift.common.bean.project.po.Project;
import com.knowswift.common.bean.project.vo.ModulePermissionVO;
import com.knowswift.common.bean.project.vo.ModuleVO;
import com.knowswift.common.bean.project.vo.ProjectLimit;
import com.knowswift.common.bean.project.vo.ProjectVO;
import com.knowswift.common.common.Assert;
import com.knowswift.common.common.BaseResponse;
import com.knowswift.common.common.GlobalProperty;
import com.knowswift.common.common.Page;
import com.knowswift.common.enums.ModuleType;
import com.knowswift.common.enums.RoleEnum;
import com.knowswift.common.utils.EntityUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.log.aop.AopLog;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/admin/project/")
public class ProjectController extends AbstractController {


    @PostMapping("/saveModule")
    @PreAuthorize("@userService.checkAuthority('editProject')")
    @AopLog(name = "保存模块", platform = "管理后台")
    public BaseResponse saveModule(@Validated @RequestBody ModuleVO param) {
        System.out.println("保存模块=====================>"+param);
        List<ProjectVO> projectVOS = param.getProjects();
        if (CollectionUtils.isEmpty(projectVOS)) {
            projectVOS = new ArrayList<>();
        } else {
            Set<String> strings = new HashSet<>();
            for (ProjectVO project : projectVOS) {
                if (strings.contains(project.getProjectName())) {
                    return BaseResponse.failure("同一模块下，项目名称不可重复");
                } else {
                    strings.add(project.getProjectName());
                }
            }
        }
        projectVOS = projectVOS.stream().sorted(Comparator.comparing(ProjectVO::getProjectOrder)).collect(Collectors.toList());
        List<Project> projectList = WrappedBeanCopier.copyPropertiesOfList(projectVOS, Project.class);
        if (StringUtils.isBlank(param.getModuleId())) {
            Integer count = moduleService.lambdaQuery().eq(Module::getModuleName, param.getModuleName()).count();
            Assert.isTrue(count == 0, "名称已存在，不可重复");
            Module module = new Module();
            module.setModuleName(param.getModuleName());
            module.setModuleOrder(param.getModuleOrder());
            module.setCreateTime(null);
            module.setProjects(projectList);
            module.setMonitorInterval(GlobalProperty.DEFAULT_MONITOR_INTERVAL); // 默认上传间隔为6小时
            // 类型功能为 预留功能
            module.setModuleType(ModuleType.PREVENTION_AND_CURE.getValue());
            EntityUtils.setCode(module, moduleService);
            boolean save = moduleService.save(module);
            return BaseResponse.condition(save, "添加失败");
        }
        Module module = moduleService.getById(param.getModuleId());
        Assert.notNull(module, "数据不存在");
        String moduleName = module.getModuleName();
        if (!moduleName.equals(param.getModuleName())) {
            Integer count = moduleService.lambdaQuery().eq(Module::getModuleName, param.getModuleName()).count();
            Assert.isTrue(count == 0, "模块名称已存在，不可重复");
        }
        module.setModuleName(param.getModuleName());
        module.setModuleOrder(param.getModuleOrder());
        module.setProjects(projectList);
        boolean update = moduleService.updateById(module);
        asyncTask.updateData(module.getModuleId(), moduleName, param.getModuleName(), projectVOS);
        asyncTask.updateMonitorData(moduleName, param.getModuleName(), projectVOS);
        return BaseResponse.condition(update, "修改失败");
    }

    @PostMapping("/modules")
    @PreAuthorize("@userService.checkAuthority('projects')")
    @AopLog(name = "模块列表", platform = "管理后台")
    public BaseResponse modules(@RequestBody ModuleVO param, Authentication authentication) {
        User user = (User) authentication.getPrincipal();
        Page<ModuleVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = moduleService.getBaseMapper().getList(param.getKeyword(), 0,null, page);
        if (!RoleEnum.isAdmin(user.getRole())) {
            page.getRecords().forEach(r -> r.setMonitorInterval(null));
        }
        return BaseResponse.success(page);
    }

    @PostMapping("/moduleList")
//    @PreAuthorize("@userService.checkAuthority('projects')")
//    @AopLog(name = "模块列表", platform = "管理后台")
    public BaseResponse modules2(@RequestBody ModuleVO param, Authentication authentication) {
        User user = (User) authentication.getPrincipal();
//
//        boolean allIssues = UserService.checkAuthority(user, "allIssues");
//        boolean ownIssues = UserService.checkAuthority(user, "ownIssues");
//        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");
//        String userId = allIssues || projectIssues ? null : user.getUserId();
//        List<String> strings = null;
//
//        if (!allIssues && !ownIssues && projectIssues) {
//            strings = new ArrayList<>();
//            List<ModulePermissionVO> permissions = modulePermissionService.getBaseMapper().getByUserId(user.getUserId());
//            for (ModulePermissionVO permission : permissions) {
//                strings.add(permission.getModuleName());
//            }
//        }
//
//        Page<ModuleVO> page = new Page<>(param.getPageNo(), param.getPageSize());
//        page = moduleService.getBaseMapper().getList(param.getKeyword(), 0,strings, page);
//        if (!RoleEnum.isAdmin(user.getRole())) {
//            page.getRecords().forEach(r -> r.setMonitorInterval(null));
//        }
//        return BaseResponse.success(page);

        Page<Module> page = new Page<>(param.getPageNo(), param.getPageSize());
        boolean allIssues = UserService.checkAuthority(user, "allIssues");
        boolean ownIssues = UserService.checkAuthority(user, "ownIssues");
        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");
        if (!allIssues && !ownIssues && projectIssues) {
            Page<ModuleVO> page1 = new Page<>(param.getPageNo(), param.getPageSize());
            Page<ModulePermissionVO> voPage = modulePermissionService.getBaseMapper().getByUserIdPage(user.getUserId(), page1);
            modulePermissionService.concatData(voPage.getRecords());
            return BaseResponse.success(voPage);
        }
        page = moduleService.lambdaQuery().select(Module::getModuleName, Module::getProjects).orderByAsc(Module::getModuleOrder).page(page);
        return BaseResponse.success(page);
    }

    @PostMapping("/deleteModule")
    @PreAuthorize("@userService.checkAuthority('editProject')")
    @AopLog(name = "删除模块", platform = "管理后台")
    public BaseResponse deleteModule(@RequestBody ModuleVO param) {
        boolean result = moduleService.removeById(param.getModuleId());

        //TODO 关联的装置和记录需要删除
        LambdaQueryWrapper<MonitorDevice> monitorDeviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<MonitorRecord> monitorRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Issue> issueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        monitorDeviceLambdaQueryWrapper.eq(MonitorDevice::getModuleName,param.getModuleName());
        monitorRecordLambdaQueryWrapper.eq(MonitorRecord::getModuleName,param.getModuleName());
        issueLambdaQueryWrapper.eq(Issue::getModuleName,param.getModuleName());
        monitorDeviceService.remove(monitorDeviceLambdaQueryWrapper);
        monitorRecordService.remove(monitorRecordLambdaQueryWrapper);
        issueService.remove(issueLambdaQueryWrapper);

        return BaseResponse.condition(result, "删除失败");
    }
}
